package main

fun main(args: Array<String>) {
    val testArray = arrayOf("帮我打开第1册", "帮我打开第一册", "帮我打开第十一册", "帮我打开第二十册", "帮我打开第二十一册")

    testArray.forEach {
        val bookNumber = getBookNumber(it)
        println(bookNumber)
    }

    println(-1 in 1..testArray.size)
}

fun getBookNumber(str: String): Int {
    val bookPattern1Cn = Regex("""第[\d]+册""")
    val bookPattern2Cn = Regex("""第[一二三四五六七八九十]+册""")
    val find1: MatchResult? = bookPattern1Cn.find(str, 0)
    var num = -1
    if (find1 != null) {
        val value = find1.value
        num = getNumberString(value).toInt()
    } else {
        val find2 = bookPattern2Cn.find(str, 0)
        find2?.apply {
            num = parseChineseToInteger(getNumberString(value))
        }
    }
    return num
}

fun getNumberString(value: String): String {
    //截取数字部分
    return value.substring(1, value.lastIndex)
}


/**
 * 将中文数字转换成阿拉伯数字100以内，配合前面的正则表达式
 */
private fun parseChineseToInteger(str: String): Int {
    val index = str.lastIndexOf("十")
    //代表不包含十
    if (index == -1) {
        return when (str) {
            "零" -> 0
            "一" -> 1
            "二" -> 2
            "三" -> 3
            "四" -> 4
            "五" -> 5
            "六" -> 6
            "七" -> 7
            "八" -> 8
            "九" -> 9
            else -> 0
        }
    } else {
        //包含十
        return if (index == 0 && index == str.lastIndex) {
            //仅有十
            10
        } else if (index == 0 && index != str.lastIndex) {
            //十开头
            10 + parseChineseToInteger(str.substring(index + 1))
        } else if (index != str.lastIndex) {
            //十在中间
            10 * parseChineseToInteger(str.substring(0, index)) + parseChineseToInteger(str.substring(index + 1))
        } else {
            //十在末尾
            parseChineseToInteger(str.substring(0, index)) * 10
        }
    }
}
